<?php
/**
 * Created by PhpStorm.
 * User: tomxia
 * Date: 2017/11/30
 * Time: 18:22
 */
namespace app\cls\tom;


class Visitor
{
    private  $secret = "77881122@()1$32";
    private $key = "vir_ID";
    private $timeOut = 86400*365*10;


    public function getDecryptVisitorId()
    {
        $virID = $this->getEncryptVisitorId();
        if($virID){
            $arr = explode("_",$virID);
            if(count($arr) == 2 && md5($arr[0].$this->secret) == $arr[1]){
                return $arr[0];
            }
        }
        return '';
    }
    public function getEncryptVisitorId()
    {
        $virID = isset($_COOKIE[$this->key]) ? $_COOKIE[$this->key] : (isset($_GET[$this->key]) ? $_GET[$this->key] : (isset($_POST[$this->key]) ? $_POST[$this->key] :""));
        if($virID){
            return $virID;
        }else{
            return "";
        }
    }

    /**
     * @param null $cache
     * @return array  [client_id,server_id]
     */
    public function getVisitorId($cache = null)
    {
        $virID = $this->getDecryptVisitorId();
        if($virID){
            return [$this->getEncryptVisitorId(),$virID];
        }
        $id = ip2long($_SERVER['HTTP_HOST']).(microtime(true)*10000).rand(1000,2000);
        if($cache){
            $autoIncrIndex = $cache->incr("common_visitor_id",1);
            $id.= sprintf("%04d",$autoIncrIndex%10000);
        }
        ob_clean();
        $value = $id."_".md5($id.$this->secret);
        return [$value,$id];
    }

}